from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from pydantic import BaseModel
from app.core.database import get_db
from app.core.deps import get_current_admin_user
from app.models.user import User
from app.models.apartment_type import ApartmentType

router = APIRouter()

class PlanResponse(BaseModel):
    id: int
    type_code: str
    type_name: str
    plan_image_url: str | None
    description: str | None

    class Config:
        from_attributes = True

class PlanUpdate(BaseModel):
    plan_image_url: str
    description: str | None = None

@router.get("", response_model=List[PlanResponse])
def get_plans(db: Session = Depends(get_db)):
    plans = db.query(ApartmentType).all()
    return plans

@router.get("/{type_code}", response_model=PlanResponse)
def get_plan(type_code: str, db: Session = Depends(get_db)):
    plan = db.query(ApartmentType).filter(
        ApartmentType.type_code == type_code
    ).first()
    if not plan:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="方案不存在"
        )
    return plan

@router.put("/{type_code}", response_model=PlanResponse)
def update_plan(
    type_code: str,
    plan_update: PlanUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    plan = db.query(ApartmentType).filter(
        ApartmentType.type_code == type_code
    ).first()
    if not plan:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="方案不存在"
        )
    
    plan.plan_image_url = plan_update.plan_image_url
    if plan_update.description:
        plan.description = plan_update.description
    
    db.commit()
    db.refresh(plan)
    return plan

